package com.iflytek.iot.redis.sharding.core;

import com.iflytek.iot.redis.sharding.core.constants.RedisShardingConstants;
import com.iflytek.iot.redis.sharding.core.entity.SlotConfig;

import java.util.List;
import java.util.Set;

/**
 * @author ZuRun
 * @date 2020/2/28 16:35:48
 */
public class RedisShardingManager<T> extends RedisClientPool<T> implements IRedisShardingManager<T> {
    private RedisShardingManager() {
    }

    private static RedisShardingManager redisClientManager = new RedisShardingManager<>();

    public static RedisShardingManager getInstance() {
        return redisClientManager;
    }

    @Override
    public Set<String> getGroupList() {
        return getGroupSlotClientMapper().keySet();
    }

    @Override
    public SlotConfig getSlotConfigByKey(String groupName, String key) {
        return super.getSlotConfigByKey(groupName, key);
    }

    @Override
    public SlotConfig getSlotConfigBySlot(String groupName, String slot) {
        return super.getSlotConfigBySlot(groupName, slot);
    }

    @Override
    public List<SlotConfig> getSlotsConfig(String groupName) {
        return super.getSlotsConfig(groupName);
    }

    @Override
    public void register(T resource, SlotConfig slotConfig) {
        register(RedisShardingConstants.DEFAULT_REDIS_GROUP, resource, slotConfig);
    }

    @Override
    public synchronized void register(IRedisGroup redisGroup, T resource, SlotConfig slotConfig) {
        final String groupName = redisGroup.getGroupName();
        /**
         * 如果group对应的对象未实例化,则实例化
         */
        GroupDetail<T> groupDetail = getGroupSlotClientMapper().get(groupName);
        if (groupDetail == null) {
            groupDetail = new GroupDetail(groupName, resource, slotConfig);
            getGroupSlotClientMapper().put(groupName, groupDetail);
        } else {
            groupDetail.add(resource, slotConfig);
        }
    }

}
